<?php
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\user\moments;

use think\facade\Db;
use think\facade\Session;
use app\wework\controller\Base;
use app\wework\model\user\moments\WeChatMomentsModel;
use app\wework\model\Basemodel;
use app\wework\model\QyWechatApi;
use think\facade\Log;
use app\wework\model\Helper;
include "../extend/PHPExcel/php-excel.class.php";

//企微朋友圈
class WeChatMoments extends Base{
	/*
	* 企微朋友圈 首页
	**/
	public function index(){
		$page = $this->req->param("page")?:1;
		$size = $this->req->param("size")?:10;
		$staffs = $this->req->param("staffs");
		$times = $this->req->param("times");
		$name = $this->req->param("name");
		$type = $this->req->param("type")?:0;
		$res = WeChatMomentsModel::list($page,$size,$staffs,$times,$name,$type);

		return success("获取成功",$res);
	}

	/*
	* 新建朋友圈
	*/
	public function addMoments(){
		$wid = Session::get("wid");
		$name = $this->req->param("name");
		if(!$name)return error("请输入名称");
		$type = $this->req->param("type");
		$staffs = $this->req->param("staffs");
		if(!$staffs)return error("请选择使用成员");
		$staffstr = [];
        foreach($staffs as $value){
            $staffstr[] = strval($value);
        }
		$customer_type = $this->req->param("customer_type");
		$tags = $this->req->param("tags");
		$text = $this->req->param("text");
		$content = $this->req->param("content");
		$send_status = $this->req->param("send_status");
		$send_time = $this->req->param("send_time");
		$res = WeChatMomentsModel::add($name,$type,$staffs,$customer_type,$tags,$text,$content,$send_status,$send_time,$staffstr);
		if(!$res)return error("添加失败");
		if($send_status == 1){
			if($type == 1){
				$userids = WeChatMomentsModel::users($staffs);
				$attachments = NULL;
				if($content)$attachments = $this->attachments($content);
				$task = QyWechatApi::addMomentTask($userids,$tags,$text,$attachments);
				if($task["errcode"] != 0)return error("接口错误",$task["errcode"]);
				$moment = QyWechatApi::getMomentTask($task["jobid"],$wid);
				if(!isset($moment["result"])){
					while (1){
						$moment = QyWechatApi::getMomentTask($task["jobid"],$wid);
						if(isset($moment["result"]))break;
					}
				}
				WeChatMomentsModel::save($res,$task["jobid"],$moment["result"]["moment_id"]);
			}else{
				$userids = implode("|",WeChatMomentsModel::users($staffs));
				$send = "【任务提醒】您有新的任务哦！";
				$send .= "<br>";
				$send .= "任务类型：发送企微朋友圈";
				$send .= "<br>";
				$send .= "创建时间：".date("Y-m-d H:i:s");
				$send_res = QyWechatApi::send_textcard($userids,$wid,"企微朋友圈提醒",$send,$this->req->domain().'/wework/h5.WeChatMoments/index.html?id='.$res);
			}
		}

		return success("添加成功",$res);
	}

	//详情
	public function detail(){
		$wid = Session::get("wid");
		$id = $this->req->param("id");
		if(!$id)return error("参数错误");
		$type = $this->req->param("type");
		$res = WeChatMomentsModel::info($id,$type);

		return success("获取成功",$res);
	}


	//提醒发送
	public function remind(){
		$wid = Session::get("wid");
		$id = $this->req->param("id");
		$userid = $this->req->param("userid");
		$res = WeChatMomentsModel::infos($id);
		if($userid){
			$send = "【任务提醒】您有新的任务哦！";
			$send .= "<br>";
			$send .= "任务类型：发送企微朋友圈";
			$send .= "<br>";
			$send .= "创建时间：".date("Y-m-d H:i:s");
			$send .= "<br>";
			$send .= "可前往【客户朋友圈】中确认发送，记得及时完成哦";
			$send_res = QyWechatApi::sendText($wid,$userid,$send);
		}else{
			$userids = implode("|",WeChatMomentsModel::staffs($res["id"]));
			$send = "【任务提醒】您有新的任务哦！";
			$send .= "<br>";
			$send .= "任务类型：发送企微朋友圈";
			$send .= "<br>";
			$send .= "创建时间：".date("Y-m-d H:i:s");
			$send .= "<br>";
			$send .= "可前往【客户朋友圈】中确认发送，记得及时完成哦";
			$send_res = QyWechatApi::send_textcard($userids,$wid,"企微朋友圈提醒",$send,$this->req->domain().'/wework/h5.WeChatMoments/index.html?id='.$res["id"]);
		}

		if($send_res["errcode"] != 0)return error("操作失败".$send_res["errmsg"]);
		return success("操作成功");
	}

	public function attachments($content){
		$data = [];
		$wid = Session::get("wid");
		if($content["type"] == 1){
			foreach($content["image_list"] as $image){
				$data[] = [
					"msgtype"=>"image",
					"image"=>[
						"media_id"=>QyWechatApi::uploadAttachment($wid,$image,"image")["media_id"]
					]
				];
			}
		}else if($content["type"] == 2){
			$data[] = [
				"msgtype"=>"video",
				"video"=>[
					"media_id"=>QyWechatApi::uploadAttachment($wid,$content["video_url"],"video")["media_id"]
				]
			];
		}else if($content["type"] == 3){
			$data[] = [
				"msgtype"=>"link",
				"link"=>[
					"url"=>$content["link_url"],
					"title"=>$content["link_title"],
					"media_id"=>QyWechatApi::uploadAttachment($wid,$content["link_imageurl"],"image")["media_id"]
				]
			];
		}
		return $data;
	}

	/*
	* 同步
	*/
	public function sync(){
		$wid = Session::get("wid");
		$data = QyWechatApi::getMomentList($wid);
		$res = WeChatMomentsModel::sync($data["moment_list"]);

		return success("获取成功",$res);
	}

	public function syncs(){
		$wid = Session::get("wid");
		$sync_list = WeChatMomentsModel::syncList();
		$mh = curl_multi_init();
        $conn = [];
        $res = [];
        $url = $this->req->domain()."/wework/user/moments/qysyncs";
        for ($i=0;$i<count($sync_list);$i++) {
            $data = http_build_query(["data"=>$sync_list[$i],"wid"=>$wid]);
            $conn[$i]=curl_init($url);
            curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1); //如果成功只将结果返回，不自动输出任何内容
            curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
            curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $data); //post 传参
            curl_multi_add_handle ($mh,$conn[$i]);
        }
        do { $n=curl_multi_exec($mh,$active); }
        while ($active);
        $result = true;
        for ($i=0;$i<count($sync_list);$i++) {
            $res[$i]=curl_multi_getcontent($conn[$i]);
            curl_close($conn[$i]);
            if($res[$i] != 1){
                $result = false;
            }
        }

        return success("同步成功");
	}

	public function qySync(){
		$data = $_POST["data"];
        $wid = $wid;
        $res = WeChatMomentsModel::syncs($data,$wid);

		return success("获取成功",$res);
	}

	//批量导出 列表
	public function downexcelList(){
		$wid = $this->req->param("wid");
		$type = $this->req->param("type");
		$res = WeChatMomentsModel::list(1,999,NULL,NULL,NULL,$type,$wid);
		$arr = [
            0 => ["标题","朋友圈内容","发布方式","朋友圈类型","创建时间","已发送成员数量","未发送成员数量"]
        ];
		$i = 1;
		foreach($res["item"] as $value){
			$arr[$i]['标题'] = $value["name"];
			$arr[$i]['朋友圈内容'] = $value["text"];
			if($value["send_status"] == 1)$arr[$i]['发布方式'] = "立即发布";
			if($value["send_status"] == 2)$arr[$i]['发布方式'] = "定时发布";
			if($value["type"] == 1)$arr[$i]['朋友圈类型'] = "企业朋友圈";
			if($value["type"] == 2)$arr[$i]['朋友圈类型'] = "个人朋友圈";
			$arr[$i]['创建时间'] = $value["ctime"];
			$arr[$i]['已发送成员数量'] = $value["yes_send"];
			$arr[$i]['未发送成员数量'] = $value["not_send"];
            $i++;
		}
		$str = "朋友圈列表-";
        if($type == 1)$str .= "企微朋友圈";
        if($type == 0)$str .= "个人朋友圈";
        $xls = new \Excel_XML('utf-8', false, '数据导出');
        $xls->addArray($arr);
        $xls->generateXML($str.date('Y-m-d H:i:s'),time());
        exit();
	}

	// 批量导出， 详情
	public function downexcel(){
		$id = $this->req->param("id");
		$type = $this->req->param("type");
		if(!$id)return error("参数错误");
		$res = WeChatMomentsModel::infos($id);
		$wid = $res["wid"];
		$data = QyWechatApi::getMoment($wid,$res["moment_id"]);
		$where["pid"] = $id;
		$where["staff_id"] = $res["staffs"];
		if(isset($type))$where["type"] = $type;
		$customer_type = $res["customer_type"];
		$tags = $res["tags"];
		$staff_list = WeChatMomentsModel::staffList($where,$wid,$customer_type,$tags,$res);
		$arr = [
            0 => ['员工名称', '员工发表状态', '发送时间','已送达客户数']
        ];
		$i = 1;
        foreach($staff_list as $staff){
        	$arr[$i]['员工名称'] = $staff["staff"]["name"];
            $arr[$i]['员工发表状态'] = $staff["type"]?"已发送":"未发送";
            $arr[$i]['发送时间'] = $staff["create_time"];
            $arr[$i]['已送达客户数'] = $staff["customer_szie"];
            $i++;
        }
        $str = "朋友圈详情-";
        if($type == 1)$str .= "已发送成员";
        if($type == 0)$str .= "未发送成员";
        if(!$type)$str .= "全部发送成员";
        $xls = new \Excel_XML('utf-8', false, '数据导出');
        $xls->addArray($arr);
        $xls->generateXML($str.date('Y-m-d H:i:s'),time());
        exit();
	}

}